<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests\UserRequest;

class UsersController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware('auth',['except' => 'show']);
    }

    public function show(User $user)
    {
        return view('users.show',compact('user'));
    }

    public function edit(User $user)
    {
        $this -> authorize('update',$user);
        return view('users.edit',compact('user'));
    }

    public function update(UserRequest $requset,User $user,ImageUploadHandler $uploadHandler)
    {
        //
        $this -> authorize('update',$user);
        $data = $requset -> all();

        if($requset->avatar){
            $result = $uploadHandler -> save($requset->avatar,'avatars',$user->id,362);
            if ($result){ //注意 if ($result) 的判断是因为 ImageUploadHandler 对文件后缀名做了限定，不允许的情况下将返回 false
                $data['avatar'] = $result['path'];
            }
        }

        $user->update($data);
        return redirect()->route('users.show',$user->id)->with('success', '个人资料更新成功！');
    }
}
